﻿using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;

namespace Foundation.Converters
{
    public class DefaultConverter : MarkupExtension, IValueConverter
    {
        public object DefaultValue { get; set; }

        public DefaultConverter()
        {
        }

        public DefaultConverter(object defaultValue)
        {
            DefaultValue = defaultValue;
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var defaultValue = DefaultValue;
            if (defaultValue is string)
                defaultValue = TypeDescriptor.GetConverter(targetType).ConvertFromString(defaultValue.ToString());
            return value ?? defaultValue ?? Default(targetType);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }

        public static object Default(Type type)
        {
            return type.IsValueType ? Activator.CreateInstance(type) : null;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }
    }
}
